package NCR.jbcz.L4_11;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by dell on 2018/2/20.
 * 输入任一年的年数,然后打印出该年的日历
 */
public class Calendar {
    static int year;//打印哪一年的日历
    static int weekDay;//该年的第一天是星期几

    public static void main(String[] args) throws IOException {
        System.out.println("请输入年份:");
        InputStreamReader ir;
        BufferedReader in;
        ir = new InputStreamReader(System.in);
        in = new BufferedReader(ir);
        String s = in.readLine();
        year = Integer.parseInt(s);
        if (year < 1) {
            System.out.println("输入的年份不能小于1!");
            return;
        }
        weekDay = (int) firstDayOfYear(year);//计算该年第一天是周几
        System.out.println("                    " + year + "年");
        System.out.println("=========================================================================");
        for (int i = 1; i < 12; i++) {
            System.out.println();
            printMonth(i);
            System.out.println();
        }
    }

    private static long firstDayOfYear(int y) {/**计算每年的第一天是周几*/
        long n;
        n = y * 365;
        for (int i = 1; i < y; i++) {
            if (isLeapYear(i)) {
                n += 1;
            }
        }
        return n %= 7;
    }

    private static boolean isLeapYear(int y) {/**判断是不是闰年*/
        return (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0));
    }


    private static void printMonth(int m) {/**打印每月日期*/
        printHead(m);
        int days = dayOfMonth(m);
        for (int i = 1; i < days; i++) {
            if (i < 10) {
                System.out.print("" + i);
            } else {
                System.out.print("       " + i);
            }
            weekDay = (weekDay + 1) % 7;
            if (weekDay == 0) {
                System.out.println();
                System.out.print("       ");
            }
        }

    }

    private static int dayOfMonth(int m) {/**返回每月的天数*/
        switch (m) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return 31;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            case 2:
                if (isLeapYear(year)) {
                    return 29;
                } else {
                    return 28;
                }
        }
        return 0;
    }

    private static void printHead(int m) {//打印每周星期标题
        System.out.println("   " + m + "月    日    一    二    三     四     五     六 ");
        System.out.print("     ");
        for (int i = 0; i < weekDay; i++) {
            System.out.print(" ");

        }
    }
}
